package com.stockz.equity.indicator.ord;

import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import org.springframework.stereotype.Component;

import com.stockz.equity.indicator.Indicator;
import com.stockz.equity.model.Bar;
import com.stockz.equity.model.Bar.BarValueType;
import com.stockz.equity.util.ListUtil;

@Component
public class OrdIndicator implements Indicator<OrdIndicatorConfiguration> {

	private OrdIndicatorConfiguration ordIndicatorConfiguration = new OrdIndicatorConfiguration();
	public static final NumberFormat numberFormat = new DecimalFormat("#0.0");
	private BarValueType barValueType = BarValueType.AVGPRICE;
	
	public List<OrdSwing> getOrdSwingList(List<Bar> barList){
		List<Bar> extreams = ListUtil.getExtreams(barList, ordIndicatorConfiguration.getPercentage(), 
				getBarValueType());

		if(!extreams.contains(barList.get(0))){
			extreams.add(barList.get(0));
		}
		
		if(extreams != null && extreams.size() > 0){
			Collections.sort(extreams);
			List<OrdSwing> ordSwingList = new ArrayList<OrdSwing>(extreams.size());
			for(int i = 0; i < extreams.size()-1; i++){
				OrdSwing ordSwing = new OrdSwing();
				ordSwingList.add(ordSwing);
				ordSwing.setEnd(extreams.get(i));
				ordSwing.setStart(extreams.get(i+1));
				
				int startIndex = barList.indexOf(ordSwing.getStart());
				int endIndex = barList.indexOf(ordSwing.getEnd());
				
				double volumeSum = 0;
				int barCount = 0;
				
				for(int j = startIndex-1; j >= endIndex; j--){
					volumeSum += barList.get(j).getVolume();
					barCount++;
				}
				
				ordSwing.setSpan(barCount);
				ordSwing.setVolume(volumeSum);				
			}
			Collections.sort(ordSwingList);
			return ordSwingList;
		}
		return Collections.emptyList();
	}

	public double getVolume(List<Bar> barList, Bar start, Bar end){
		double volumeSum = 0;
		for(int i = barList.indexOf(start)-1; i >= barList.indexOf(end); i--){
			volumeSum += barList.get(i).getVolume();
		}
		return volumeSum;
	}
	
	public double getSpan(List<Bar> barList, Bar start, Bar end){
		return barList.indexOf(end) - barList.indexOf(start);
	}

	@Override
	public OrdIndicatorConfiguration getIndicatorConfiguration() {
		return ordIndicatorConfiguration;
	}

	@Override
	public double getValue(List<Bar> barList) {
		throw new UnsupportedOperationException();
	}
	
	@Override
	public double[] getValues(List<Bar> barList) {
		throw new UnsupportedOperationException();
	}

	public BarValueType getBarValueType() {
		return barValueType;
	}

	public void setBarValueType(BarValueType barValueType) {
		this.barValueType = barValueType;
	}
}
